package com.wenwei.activity;

import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alipay.sdk.app.PayTask;
import com.orhanobut.logger.Logger;
import com.tencent.mm.sdk.modelpay.PayReq;
import com.tencent.mm.sdk.openapi.IWXAPI;
import com.tencent.mm.sdk.openapi.WXAPIFactory;
import com.wenwei.bean.PayResult;
import com.wenwei.bean.RechargeBalanceBean;
import com.wenwei.bean.RechargeConfigBean;
import com.wenwei.bean.WeChatPayConfigBean;
import com.wenwei.net.ApiManager;
import com.wenwei.net.BaseSubscriber;
import com.wenwei.parking.BaseActivity;
import com.wenwei.parking.Constant;
import com.wenwei.parking.R;
import com.wenwei.utils.UserStringUtils;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONObject;

import java.util.ArrayList;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Created by Administrator on 2017/8/21.
 */
public class RechargeActivity extends BaseActivity {

    @Bind(R.id.base_title)
    TextView baseTitle;
    @Bind(R.id.bind_btn)
    TextView bindBtn;
    @Bind(R.id.recharge_price_1)
    TextView rechargePrice1;
    @Bind(R.id.recharge_price_2)
    TextView rechargePrice2;
    @Bind(R.id.recharge_price_3)
    TextView rechargePrice3;
    @Bind(R.id.recharge_price_4)
    TextView rechargePrice4;
    @Bind(R.id.recharge_price_5)
    TextView rechargePrice5;
    @Bind(R.id.recharge_price_6)
    TextView rechargePrice6;
    @Bind(R.id.pay_wechat_iv)
    ImageView payWechatIv;
    @Bind(R.id.pay_wechat_rl)
    RelativeLayout payWechatRl;
    @Bind(R.id.pay_aLi_iv)
    ImageView payALiIv;
    @Bind(R.id.pay_ali_rl)
    RelativeLayout payAliRl;


    private Handler mPayHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            PayResult payResults = new PayResult((String) msg.obj);
            switch (msg.what) {
                case 1: {
                    PayResult payResult = new PayResult((String) msg.obj);
                    /**
                     * 同步返回的结果必须放置到服务端进行验证（验证的规则请看https://doc.open.alipay.com/doc2/
                     * detail.htm?spm=0.0.0.0.xdvAU6&treeId=59&articleId=103665&
                     * docType=1) 建议商户依赖异步通知
                     */
                    String resultInfo = payResult.getResult();// 同步返回需要验证的信息
                    String resultStatus = payResult.getResultStatus();
                    // 判断resultStatus 为“9000”则代表支付成功，具体状态码代表含义可参考接口文档
                    if (TextUtils.equals(resultStatus, "9000")) {
                        showToast("充值成功");
                        EventBus.getDefault().post("999");
                        goActivity(mContext,RechargeSuccessActivity.class);
                    } else {
                        // 判断resultStatus 为非"9000"则代表可能支付失败
                        // "8000"代表支付结果因为支付渠道原因或者系统原因还在等待支付结果确认，最终交易是否成功以服务端异步通知为准（小概率状态）
                        if (TextUtils.equals(resultStatus, "8000")) {

                        } else {
                            // 其他值就可以判断为支付失败，包括用户主动取消支付，或者系统返回的错误
                        }
                        showToast("支付宝支付失败");
                    }
                    break;
                }
                default:
                    break;
            }
        }
    };
    @Override
    public int setLayoutResourceId() {
        return R.layout.activity_recharge;
    }

    @Override
    protected void initView() {
        super.initView();
        baseTitle.setText("充值");

    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
        EventBus.getDefault().register(this);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(String event) {
        Logger.d("支付回调："+event);
        if(event.equals("success")){
            showToast("充值成功");
            goActivity(mContext,RechargeSuccessActivity.class);
            EventBus.getDefault().post("999");
        }
    }

    private int mPayType = -1;

    private void changeSelectPayType() {
        if (mPayType == Constant.PAY_TYPE_ALI) {
            payALiIv.setImageResource(R.mipmap.btn_selected);
            payWechatIv.setImageResource(R.mipmap.btn_xuanze);
        } else if (mPayType == Constant.PAY_TYPE_WE) {
            payALiIv.setImageResource(R.mipmap.btn_xuanze);
            payWechatIv.setImageResource(R.mipmap.btn_selected);
        }
    }

    @Override
    protected void initData() {
        super.initData();
        rechargeConfig();
    }

    private BaseSubscriber<ArrayList<RechargeConfigBean>> rechargeSb;
    private ArrayList<RechargeConfigBean> mList;
    private void rechargeConfig() {
        rechargeSb = new BaseSubscriber<ArrayList<RechargeConfigBean>>(mContext) {
            @Override
            public void onSuccess(ArrayList<RechargeConfigBean> rechargeConfigBeen) {
                mList = rechargeConfigBeen;
                rechargePrice1.setText(rechargeConfigBeen.get(0).getRechargeAmount() + "赠送" +
                        rechargeConfigBeen.get(0).getGiveAmount());
                rechargePrice2.setText(rechargeConfigBeen.get(1).getRechargeAmount() + "赠送" +
                        rechargeConfigBeen.get(1).getGiveAmount());
                rechargePrice3.setText(rechargeConfigBeen.get(2).getRechargeAmount() + "赠送" +
                        rechargeConfigBeen.get(2).getGiveAmount());
                rechargePrice4.setText(rechargeConfigBeen.get(3).getRechargeAmount() + "赠送" +
                        rechargeConfigBeen.get(3).getGiveAmount());
                rechargePrice5.setText(rechargeConfigBeen.get(4).getRechargeAmount() + "赠送" +
                        rechargeConfigBeen.get(4).getGiveAmount());
                rechargePrice6.setText(rechargeConfigBeen.get(5).getRechargeAmount() + "赠送" +
                        rechargeConfigBeen.get(5).getGiveAmount());
            }
        };
        ApiManager.getInstance().rechargeConfig(rechargeSb);
    }

    private int rechargeId = -1;
    private RechargeConfigBean rechargeConfigBean;
    @OnClick({R.id.base_back, R.id.recharge_price_1, R.id.recharge_price_2, R.id.recharge_price_3, R.id.recharge_price_4, R.id.recharge_price_5, R.id.recharge_price_6, R.id.pay_wechat_rl, R.id.pay_ali_rl, R.id.bind_btn})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.base_back:
                finish();
                break;
            case R.id.recharge_price_1:
                rechargeConfigBean = mList.get(0);
                rechargeId = mList.get(0).getId();
                changeSelectPrice(1);
                break;
            case R.id.recharge_price_2:
                rechargeConfigBean = mList.get(1);
                rechargeId = mList.get(1).getId();
                changeSelectPrice(2);
                break;
            case R.id.recharge_price_3:
                rechargeConfigBean = mList.get(2);
                rechargeId = mList.get(2).getId();
                changeSelectPrice(3);
                break;
            case R.id.recharge_price_4:
                rechargeConfigBean = mList.get(3);
                rechargeId = mList.get(3).getId();
                changeSelectPrice(4);
                break;
            case R.id.recharge_price_5:
                rechargeConfigBean = mList.get(4);
                rechargeId = mList.get(4).getId();
                changeSelectPrice(5);
                break;
            case R.id.recharge_price_6:
                rechargeConfigBean = mList.get(5);
                rechargeId = mList.get(5).getId();
                changeSelectPrice(6);
                break;
            case R.id.pay_wechat_rl:
                mPayType = Constant.PAY_TYPE_WE;
                changeSelectPayType();
                break;
            case R.id.pay_ali_rl:
                mPayType = Constant.PAY_TYPE_ALI;
                changeSelectPayType();
                break;
            case R.id.bind_btn:
                if(rechargeConfigBean!=null){
                    if(mPayType == Constant.PAY_TYPE_WE){
                        rechargeBalanceWe();
                    }else if(mPayType == Constant.PAY_TYPE_ALI){
                        rechargeBalanceAli();
                    }else if (mPayType == -1){
                        showToast("请选择支付方式");
                    }
                }else {
                    showToast("请选择充值金额");
                }
                break;
        }
    }

    private void changeSelectPrice(int positio ){
        rechargePrice1.setBackgroundResource(R.drawable.button_state_6);
        rechargePrice1.setTextColor(Color.parseColor("#45bcc6"));
        rechargePrice2.setBackgroundResource(R.drawable.button_state_6);
        rechargePrice2.setTextColor(Color.parseColor("#45bcc6"));
        rechargePrice3.setBackgroundResource(R.drawable.button_state_6);
        rechargePrice3.setTextColor(Color.parseColor("#45bcc6"));
        rechargePrice4.setBackgroundResource(R.drawable.button_state_6);
        rechargePrice4.setTextColor(Color.parseColor("#45bcc6"));
        rechargePrice5.setBackgroundResource(R.drawable.button_state_6);
        rechargePrice5.setTextColor(Color.parseColor("#45bcc6"));
        rechargePrice6.setBackgroundResource(R.drawable.button_state_6);
        rechargePrice6.setTextColor(Color.parseColor("#45bcc6"));
        switch(positio){
            case 1:
                rechargePrice1.setBackgroundResource(R.drawable.button_state_2);
                rechargePrice1.setTextColor(Color.parseColor("#ffffff"));
                break;
            case 2:
                rechargePrice2.setBackgroundResource(R.drawable.button_state_2);
                rechargePrice2.setTextColor(Color.parseColor("#ffffff"));
                break;
            case 3:
                rechargePrice3.setBackgroundResource(R.drawable.button_state_2);
                rechargePrice3.setTextColor(Color.parseColor("#ffffff"));
                break;
            case 4:
                rechargePrice4.setBackgroundResource(R.drawable.button_state_2);
                rechargePrice4.setTextColor(Color.parseColor("#ffffff"));
                break;
            case 5:
                rechargePrice5.setBackgroundResource(R.drawable.button_state_2);
                rechargePrice5.setTextColor(Color.parseColor("#ffffff"));
                break;
            case 6:
                rechargePrice6.setBackgroundResource(R.drawable.button_state_2);
                rechargePrice6.setTextColor(Color.parseColor("#ffffff"));
                break;
        }
    }


    private BaseSubscriber<String> balanceSbb;
    private void rechargeBalanceAli(){
        balanceSbb = new BaseSubscriber<String>(mContext,true,"请稍后...") {
            @Override
            public void onSuccess(final String s) {
                Runnable payRunnable = new Runnable() {
                    @Override
                    public void run() {
                        PayTask alipay = new PayTask(RechargeActivity.this);
                        String result = alipay.pay(s, true);
                        Message msg = new Message();
                        msg.what = 1;
                        msg.obj = result;
                        mPayHandler.sendMessage(msg);
                    }
                };
                Thread payThread = new Thread(payRunnable);
                payThread.start();
            }
        };
        try{
            JSONObject jb = new JSONObject();
            jb.put("amount",rechargeConfigBean.getRechargeAmount());
            jb.put("giveAmount",rechargeConfigBean.getGiveAmount());
            jb.put("payType",1);
            jb.put("userId",UserStringUtils.getUserId(mContext));
            Logger.d("参数："+jb.toString());
            ApiManager.getInstance().rechargesAli(balanceSbb,jb.toString());
        }catch (Exception e){}

    }

    private BaseSubscriber<WeChatPayConfigBean> balanceSb;
    private void rechargeBalanceWe(){
        balanceSb = new BaseSubscriber<WeChatPayConfigBean>(mContext,true,"请稍后...") {
            @Override
            public void onSuccess(WeChatPayConfigBean rechargeBalanceBean) {
                weChatPayStart(rechargeBalanceBean);
            }
        };
        try{
            JSONObject jb = new JSONObject();
            jb.put("amount",rechargeConfigBean.getRechargeAmount());
            jb.put("giveAmount",rechargeConfigBean.getGiveAmount());
            jb.put("payType",2);
            jb.put("userId",UserStringUtils.getUserId(mContext));
            ApiManager.getInstance().recharges(balanceSb,jb.toString());
        }catch (Exception e){}

    }


    //微信支付签名
    BaseSubscriber<WeChatPayConfigBean> weChatSubscriber;
    private void weChatConfig(String mOrderNum) {
        weChatSubscriber = new BaseSubscriber<WeChatPayConfigBean>(mContext) {
            @Override
            public void onSuccess(WeChatPayConfigBean weChatPayConfigBean) {
                Logger.d("微信支付签名获取成功");
                weChatPayStart(weChatPayConfigBean);
            }
        };
        ApiManager.getInstance().wxPayConfig(weChatSubscriber, mOrderNum);
    }

    //支付宝签名
    BaseSubscriber<String> alipaySubscriber;
    private void aplipayConfig(String mOrderNum) {
        alipaySubscriber = new BaseSubscriber<String>(mContext) {
            @Override
            public void onSuccess(final String s) {
                Runnable payRunnable = new Runnable() {
                    @Override
                    public void run() {
                        PayTask alipay = new PayTask(RechargeActivity.this);
                        String result = alipay.pay(s, true);
                        Message msg = new Message();
                        msg.what = 1;
                        msg.obj = result;
                        mPayHandler.sendMessage(msg);
                    }
                };
                Thread payThread = new Thread(payRunnable);
                payThread.start();
            }
        };
        ApiManager.getInstance().alipayConfig(alipaySubscriber,mOrderNum);
    }

    private void weChatPayStart(WeChatPayConfigBean weChatPayBean) {
        String app_id = weChatPayBean.getAppid();
        IWXAPI iwxapi = WXAPIFactory.createWXAPI(mContext, app_id);
        iwxapi.registerApp(app_id);
        PayReq payRequest = new PayReq();
        payRequest.appId = app_id;
        payRequest.partnerId = weChatPayBean.getPartnerid();
        payRequest.prepayId = weChatPayBean.getPrepayid();
        payRequest.nonceStr = weChatPayBean.getNoncestr();
        payRequest.timeStamp = weChatPayBean.getTimestamp();
        payRequest.sign = weChatPayBean.getSign();
        payRequest.packageValue = "Sign=WXPay";
        Logger.d("appID:" + app_id + ",partnerId:" + weChatPayBean.getPartnerid() + ",prepayId:" + weChatPayBean.getPrepayid() + ",nonceStr:" + weChatPayBean.getNoncestr()
                + ",timeStamp:" + weChatPayBean.getTimestamp() + ",sign:" + weChatPayBean.getSign() + ".packageValue:Sign=WXPay");
        //发起请求
        iwxapi.sendReq(payRequest);
    }
}
